package com.deyuanyun.pic.settings.controller.base;

import com.alibaba.fastjson.JSON;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.settings.controller.dto.BizMsgThresholdVO;
import com.deyuanyun.pic.settings.controller.dto.prvlg.RoleDTO;
import com.deyuanyun.pic.settings.domain.base.Code;
import com.deyuanyun.pic.settings.enumeration.ThresholdType;
import com.deyuanyun.pic.settings.service.base.BizMsgThresholdService;
import com.deyuanyun.pic.settings.support.utils.BaseCodeUtils;
import com.deyuanyun.pic.settings.task.QuartzConsts;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  业务阀值相关controller
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-06-23
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
@Controller
@RequestMapping("/settings/bizThreshold")
public class BizMsgThresholdController {

    @Autowired
    private BizMsgThresholdService bizMsgThresholdService;

    @ModelAttribute
    public void initData(ModelMap modelMap) {
        List<RoleDTO> list = bizMsgThresholdService.queryAllRole();
        modelMap.addAttribute("roleList", JSON.toJSONString(list));//所有角色
        Map<String, String> maps = Maps.newHashMap();
        for (RoleDTO roleDTO : list) {
            maps.put(roleDTO.getId(), roleDTO.getName());
        }
        modelMap.addAttribute("roleMap", JSON.toJSONString(maps));
    }

    /**
     * 初始化业务阀值设置
     */
    @RequestMapping("/initBizThreshold.html")
    public String initializeBizThreshold(ModelMap modelMap) {
        putGradeAreaInfo(modelMap);
        return "/base/initBizThreshold";
    }


    private static Set<String> bizThresholdSets = Sets.newHashSet("RISK_EVALUATION", "INTEGRITY_ASSESSMENT", "DEFECT_EVALUATION");

    private ReentrantLock reentrantLock = new ReentrantLock();

    /**
     * 保存用户初始化业务阀值设置
     */
    @RequestMapping("/saveBizThreshold.json")
    @ResponseBody
    public void saveBizThreshold(@RequestBody List<Object> list, @RequestParam("type") String type) {
        try {
            reentrantLock.lock();
            Asserts.assertTrue(list != null || list.isEmpty(), "没有需要保存的数据");
            Asserts.assertTrue(bizThresholdSets.contains(type), "类型不在范围内");
            bizMsgThresholdService.insertBizMsgThresholdInfo(list, type);
            AjaxSupport.sendSuccessText("success", "保存成功");
        } finally {
            reentrantLock.unlock();
        }
    }

    /**
     * 转换码表的codes为List<Map<String, Object>>
     * @param codes
     * @return 
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-10-12
     */
    private List<Map<String, Object>> getCodeSelects(List<Code> codes) {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if(codes != null && !codes.isEmpty()) {
            for (Code code : codes) {
                String name = code.getName();
                if(name.contains("--")) {
                    continue;
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", name);
                map.put("id", code.getSort());
                mapList.add(map);
            }
        }
        return mapList;
    }


    /**
     * 把地区等级和风险等级放入modelMap中
     * @param modelMap
     * @return 
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-11-02
     */
    private void putGradeAreaInfo(ModelMap modelMap) {
        List<Code> areaList = BaseCodeUtils.getCodeList("RA_AREA_LEVEL");
        List<Map<String, Object>> areaMapLists = getCodeSelects(areaList);
        if(!areaMapLists.isEmpty()) {
            modelMap.addAttribute("areaLevelList", JSON.toJSONString(areaMapLists)); //地区等级
        }
        List<Code> gradeList = BaseCodeUtils.getCodeList("RA_RISK_GRADE");

        List<Map<String, Object>> gradeMapLists = getCodeSelects(gradeList);
        if(!gradeMapLists.isEmpty()) {
            modelMap.addAttribute("riskGradeList", JSON.toJSONString(gradeMapLists)); //地区等级
        }
    }

    /**
     * 跳转到风险评价页面，并带入必要数据
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/toRiskAppraise.html")
    public String toRiskAppraise(ModelMap modelMap) {
        putGradeAreaInfo(modelMap);
        return "/settings/bizThreshold/riskAppraise";
    }


    /**
     * 根据类型得到业务阀值设置页面的json信息
     * @param type
     */
    @RequestMapping("/getData.json")
    @ResponseBody
    public void getData(String type) {
        if(StringUtils.isNotEmpty(type)) {
            List<BizMsgThresholdVO> pageInfoList = bizMsgThresholdService.queryChildForPage(type);
            Map<String, BizMsgThresholdVO> map = new LinkedHashMap<String, BizMsgThresholdVO>();

            for (BizMsgThresholdVO bizMsgThresholdVO : pageInfoList) {
                if(ThresholdType.INTERNAL_INSP_RESULT_INPUT.getValue().equals(bizMsgThresholdVO.getType()) ||
                        ThresholdType.INTERNAL_INSP_INPUT_APPRAISE.getValue().equals(bizMsgThresholdVO.getType())) {
                }else {
                    map.put(bizMsgThresholdVO.getType(), bizMsgThresholdVO);
                }
            }
            AjaxSupport.sendSuccessText("success", map);
        } else {
            AjaxSupport.sendFailText("error", "");
        }
    }

    private  ReentrantLock riskLock = new ReentrantLock();

    private ReentrantLock integrityLock = new ReentrantLock();

    private ReentrantLock defectLock = new ReentrantLock();

    /**
     * 保存风险评价页面数据
     * @param map 页面传入的json数据
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/saveRiskAppraise.json")
    @ResponseBody
    public void  saveRiskAppraise(@RequestBody Map<String, Object> map) {
        try {
            riskLock.lock();
            Asserts.assertTrue(map != null || map.isEmpty() ,"请传入需要更改的数据");
            bizMsgThresholdService.updateRisk(map);
            AjaxSupport.sendSuccessText("success", "");
        } finally {
            riskLock.unlock();
        }
    }

    /**
     * 风险评价页面撤销操作
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/cancelRiskAppraise.json")
    @ResponseBody
    public void cancelRiskAppraise() {
        try {
            riskLock.lock();
            bizMsgThresholdService.updateThresPipePageCancel(ThresholdType.RISK_EVALUATION.getValue(),
                    ThresholdType.RISK_PIPE_SCHEDULE, QuartzConsts.RISK_PIPE_TASK_GROUP_NAME);
            AjaxSupport.sendSuccessText("success", "");
        } finally {
            riskLock.unlock();
        }
    }

    /**
     * 跳转到完整性评价页面，并带入必要数据
     * @param
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/toInteAss.html")
    public String toIntegrityAssessment(ModelMap modelMap) {
        return "/settings/bizThreshold/integrityAssessment";
    }

    /**
     * 保存完整性评价页面数据
     * @param map 页面传入的json数据
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/saveInteAss.json")
    @ResponseBody
    public void saveIntegrityAssessment(@RequestBody Map<String, Object> map) {
        try {
            integrityLock.lock();
            Asserts.assertTrue(map != null || map.isEmpty() ,"请传入需要更改的数据");
            bizMsgThresholdService.updateIntegrity(map);
            AjaxSupport.sendSuccessText("success", "");
        } finally {
            integrityLock.unlock();
        }
    }

    /**
     * 完整性评价页面撤销操作
     * @param
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/cancelInteAss.json")
    @ResponseBody
    public void cancelIntegrityAssessment() {
        try {
            integrityLock.lock();
            bizMsgThresholdService.updateThresPipePageCancel(ThresholdType.INTEGRITY_ASSESSMENT.getValue(),
                    ThresholdType.INTERNAL_INSP_PIPE_SCHEDULE, QuartzConsts.INSP_TASK_GOURP_NAME);
            AjaxSupport.sendSuccessText("success", "");
        } finally {
            integrityLock.unlock();
        }
    }

    /**
     * 跳转到缺陷评价页面，并带入必要数据
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/toDefectEvaluation.html")
    public String toDefectEvaluation(ModelMap modelMap) {
        List<Code> areaList = BaseCodeUtils.getCodeList("RA_AREA_LEVEL");
        List<Map<String, Object>> areaMapLists = getCodeSelects(areaList);
        if(!areaMapLists.isEmpty()) {
            modelMap.addAttribute("areaLevelList", JSON.toJSONString(areaMapLists)); //地区等级
        }
        return "/settings/bizThreshold/defectEvaluation";
    }


    /**
     * 缺陷评价页面保存操作
     * @param map
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/saveDefeEval.json")
    @ResponseBody
    public void saveDefectEvaluation(@RequestBody Map<String, Object> map) {
        try {
            defectLock.lock();
            Asserts.assertTrue(map != null || map.isEmpty() ,"请传入需要更改的数据");
            bizMsgThresholdService.updateDefectEvaluation(map);
            AjaxSupport.sendSuccessText("success", "");
        } finally {
            defectLock.unlock();
        }
    }

    /**
     * 缺陷评价页面撤销操作
     * @param
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-06-23
     */
    @RequestMapping("/cancelDefeEval.json")
    @ResponseBody
    public void cancelDefectEvaluation() {
        try {
            defectLock.lock();
            bizMsgThresholdService.updateThresholdPageCancel(ThresholdType.DEFECT_EVALUATION.getValue());
            AjaxSupport.sendSuccessText("success", "");
        } finally {
            defectLock.unlock();
        }
    }

}
